<!-- Created by henian.xu on 2018/8/13. -->

<template>
    <div class="upload-wrap">
        <div class="upload-list">
            <div
                class="item"
                v-for="(item) in uploadFiles"
                :key="item.id"
            >
                <div
                    class="inner"
                    :style="`background-image: url('${item.url || item.address || $defaultImg}');`"
                />
                <div :class="['ctrl-wrap',{uploading:item.status==='uploading'}]">
                    <el-progress
                        v-if="item.status==='uploading'"
                        type="circle"
                        :percentage="item.percentage|number(0)"
                        :width="80"
                    />
                    <template
                        v-if="item.status==='success'"
                    >
                        <i
                            class="icon el-icon-delete"
                            @click="onDelete(item)"
                        />
                        <i
                            class="icon el-icon-search"
                            @click="onPreview(item)"
                        />
                    </template>
                </div>
            </div>
            <el-upload
                list-type="picture"
                :show-file-list="false"
                v-show="!isLimit"
                ref="ELUpload"
                class="ELUpload"
                :action="action"
                :headers="headers"
                :accept="accept"
                multiple
                :limit="limit"
                :on-change="onChange"
                :before-upload="beforeUpload"
                :on-success="onSuccess"
                :on-exceed="onExceed"
                :file-list="VFileList"
            >
                <i class="el-icon-plus"/>
            </el-upload>
        </div>
        <div
            v-if="tips"
            slot="tip"
            class="el-upload__tip">
            {{ tips }}
        </div>
        <el-dialog 
            :visible.sync="previewDialog.visible" 
            append-to-body>
            <img
                width="100%"
                :src="previewDialog.url"
                alt="">
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: 'Upload',
    data() {
        return {
            VFileList: [],
            isMounted: false,
            previewDialog: {
                visible: false,
                url: '',
            },
        };
    },
    props: {
        value: {
            type: Array,
            default() {
                return [];
            },
        },
        action: {
            type: String,
            required: true,
        },
        limit: {
            type: Number,
            default: 0,
        },
        tips: {
            type: String,
            default: '只能上传jpg/png文件，且不超过500kb',
        },
        accept: {
            type: String,
            default: '',
        },
        beforeUpload: {
            type: Function,
            default: () => {},
        },
        returnFiles: {
            type: Boolean,
            default: false,
        },
    },
    computed: {
        $$ELUpload() {
            const { ELUpload } = this.$refs;
            const { isMounted } = this;
            if (!ELUpload || !isMounted) return null;
            return ELUpload;
        },
        uploadFiles() {
            const { $$ELUpload } = this;
            if (!$$ELUpload) return [];
            return $$ELUpload.uploadFiles;
        },
        fileMap() {
            return this.uploadFiles.reduce((prev, curr) => {
                prev[curr.uid] = curr;
                return prev;
            }, {});
        },
        isComplete() {
            const { uploadFiles } = this;
            if (!uploadFiles || !uploadFiles.length) return true;
            return !uploadFiles.some(item => {
                return item.status !== 'success';
            });
        },
        isLimit() {
            const { limit, uploadFiles } = this;
            if (typeof limit === 'number') {
                return uploadFiles.length === limit;
            } else {
                return false;
            }
        },
        headers() {
            return {
                // token: this.$config.AXIOS_DEFAULT_CONFIG.headers.token,
                token: this.$store.getters['user/token'],
            };
        },
    },
    watch: {
        value: {
            handler(val) {
                // console.log(val);
                if (val.__isInnerCtrl) return;
                this.VFileList = val.map(item => {
                    const data = { ...item };
                    data.url = data.address;
                    data.isOutside = true;
                    return data;
                });
            },
            immediate: true,
        },
    },
    methods: {
        onChange(/*file, fileList*/) {
            // file.status ready:就绪;uploading:上传中;success:上传成功;fail:上传失败;
            // const {fileMap} = this;
            // console.log('onChange', file === fileList[0], {...file}, fileList, fileMap);
        },
        onSuccess() {
            // console.log('onSuccess');
            const { uploadFiles } = this;
            const value = [];
            if (this.returnFiles) {
                uploadFiles.filter(item => item.status === 'success').map(item => {
                    const isOutside = item.isOutside;
                    const data = isOutside ? item : item.response.data;
                    value.push({
                        ...item,
                        name: data.name,
                        address: data.address,
                    });
                });
            } else {
                uploadFiles.forEach(item => {
                    if (item.status !== 'success') return;
                    const isOutside = item.isOutside;
                    const data = isOutside ? item : item.response.data;
                    value.push({
                        name: data.name,
                        address: data.address,
                    });
                });
            }
            value.__isInnerCtrl = true;
            this.$emit('input', value);
        },
        onExceed() {
            // console.log('onExceed');
            this.$message.error(`最多只能上传 ${this.limit} 张`);
        },
        onDelete(file) {
            // console.log('onDelete');
            const { $$ELUpload } = this;
            $$ELUpload.handleRemove(file);
            this.onSuccess();
        },
        onPreview(file) {
            // console.log('onPreview');
            this.previewDialog = {
                visible: true,
                url: file.url,
            };
        },
        clear() {
            this.VFileList = [];
        },
    },
    mounted() {
        this.isMounted = true;
    },
};
</script>

<style lang="scss">
$itemWidth: 100px !default;
.upload-wrap {
    > .upload-list {
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        flex-wrap: wrap;
        > .item {
            position: relative;
            width: $itemWidth;
            border: 1px solid $gray5;
            background-color: $gray3;
            border-radius: 3px;
            margin-right: $margin;
            > .inner {
                width: 100%;
                padding-top: 100%;
                background-position: center;
                background-repeat: no-repeat;
                background-size: cover;
            }
            > .ctrl-wrap {
                display: none;
                /*display: flex;*/
                flex-direction: row;
                justify-content: center;
                align-items: center;
                position: absolute;
                top: 0;
                right: 0;
                bottom: 0;
                left: 0;
                background-color: rgba(0, 0, 0, 0.5);
                padding: $padding;

                > .el-progress {
                    > .el-progress__text {
                        color: #fff;
                    }
                }
                > .icon {
                    color: #fff;
                    margin: 0 $margin-small;
                }

                &.uploading {
                    display: flex;
                }
            }

            &:hover {
                > .ctrl-wrap {
                    display: flex;
                }
            }
        }
        > .ELUpload {
            position: relative;
            width: $itemWidth;
            > .el-upload {
                display: flex;
                flex-direction: row;
                justify-content: center;
                align-items: center;
                width: 100%;
                height: 0;
                padding: 50% 0;
                border: 1px dashed $color-border;
                border-radius: 3px;
                font-size: 20px;
            }
        }
    }
}
</style>
